package com.snailcatmall.www.serversocket.netty.threadTools;

import com.snailcatmall.www.serversocket.pojo.ClientInfo;
import com.snailcatmall.www.serversocket.tools.GlobalStaticClass;

import java.net.SocketAddress;
import java.util.Calendar;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

/**
 * @see NettyClientTimestampVerification 心跳检测
 */
public class NettyClientTimestampVerification  implements Runnable{
    @Override
    public void run() {
        while (true){
            try {
                offlineDetection();
            }catch (Exception e){break;}
        }
    }

    private void offlineDetection() {
        Iterator<Entry<SocketAddress, ClientInfo> >entryIterator = GlobalStaticClass.channelHandlerContextMap.entrySet().iterator();
        while (entryIterator.hasNext()){
            Entry<SocketAddress, ClientInfo> socketAddressClientInfoEntry = entryIterator.next();
            if((Calendar.getInstance().getTimeInMillis()-socketAddressClientInfoEntry.getValue().getTimeStamp())>10000 ){
                socketAddressClientInfoEntry.getValue().getChannelHandlerContext().channel().close();
                socketAddressClientInfoEntry.getValue().getChannelHandlerContext().pipeline().close();
                socketAddressClientInfoEntry.getValue().getChannelHandlerContext().close();
                entryIterator.remove();
                System.out.println("当前在线人数: " + GlobalStaticClass.channelHandlerContextMap.size() +" 位");
                break;
            }
        }
    }
}
